package com.example.demo.leetcode;

import java.util.Stack;

/**
 *
 */
public class _151_反转字符串中的单词 {

    public static void main(String[] args) {
        System.out.println(new Solution().reverseWords("a good   example"));
    }

    public static class Solution {
        /**
         * 双指针
         */
        public String reverseWords(String s) {
            String[] split = s.split(" ");
            int pre = 0;
            int suffix = split.length - 1;

            while (pre < suffix) {
                String s1 = split[pre];
                split[pre] = split[suffix];
                split[suffix] = s1;
                pre++;
                suffix--;
            }
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < split.length; i++) {
                if (!split[i].equals("")) {
                    sb.append(split[i]).append(" ");
                }
            }
            return sb.toString().trim();
        }

        /**
         * 队列
         */
        public String reverseWords2(String s) {
            String trim = s.trim();
            String[] split = trim.split(" ");
            Stack<String> stack = new Stack<>();
            for (int i = 0; i < split.length; i++) {
                if (!split[i].equals("")) {
                    stack.push(split[i]);
                }
            }
            StringBuilder sb = new StringBuilder();
            while (!stack.isEmpty()) {
                sb.append(stack.pop()).append(" ");
            }
            return sb.toString().trim();
        }
    }
}
